<template>
  <view class="container">
    <!--搜索框-->
    <view class="tui-searchbox">
      <view :style="{height: `${statusBar.top}px`, width: '100%'}"></view>
      <view class="tui-search-bar" :style="{height: `${statusBar.height}px`}">
        <tui-icon name="home-fill" color="#333" :size="22" @tap="HANDLE_JUMP_HOME"></tui-icon>
        <view class="tui-search-input" @tap="HANDLE_JUMP_PAGES('/pagesB/search/search')" :style="{marginRight: `${statusBar.menuWidth}px`}">
          <icon type="search" :size="13" color="#999"></icon>
          <text class="tui-search-text">搜索商品</text>
        </view>
      </view>
    </view>
    <!--类目content-->
    <template v-if="tabbar.length !== 0">
      <view class="tui-page-content">
        <view class="tui-content-left">
          <scroll-view scroll-y scroll-with-animation :scroll-into-view="scrollViewId" :style="{ height: `${height}px` }">
            <view :id="`id_${index}`" v-for="(item, index) in tabbar" :key="index" class="tab-bar-item" :class="[currentTab == index ? 'active' : '']" :data-current="index" @tap.stop="swichNav">
              <text>{{ item.categoryName }}</text>
            </view>
          </scroll-view>
        </view>
        <view class="tui-content-right">
          <!--block v-for="(item, index) in tabbar" :key="index">
						<scroll-view scroll-y style="height: 100%;" v-if="currentTab == index">
							<view class="page-view">
								<view class="class-box">
									<view class="class-item">
										<view class="class-name">{{ item.categoryName }}</view>
										<view v-if="Array.isArray(item.children) && item.children.length>0" class="g-container">
											<view v-for="row in item.children" :key="row.categoryCode" 
												class="g-box" 
												@tap.stop="productList($event,row)"
												:data-key="row.categoryName">
													<image :src="row.categoryPic" class="g-image" />
													<view class="g-title">{{ row.categoryName }}</view>
											</view>
										</view>
										<view class="mt20" v-else>
											<tui-no-data :fixed="false" imgUrl="https://cwmall.oss-cn-shanghai.aliyuncs.com/mp-icon/img_noorder_3x.png">暂无二级目录</tui-no-data>
										</view>
									</view>
								</view>
							</view>
						</scroll-view>
					</block-->
          <view class="sub-categorys">
            <scroll-view scroll-x="true" :style="{width: `${subCateScrollWidth}px;`}" class="sub-category-scroller">
              <view class="sub-category-item" :class="{'actived-sub-cate': cate.categoryCode === selectedSubCateCode}" v-for="cate in subCategory" :data-key="cate.categoryName" @tap.stop="subCateTaped(cate)" :key="cate.categoryCode">
                {{cate.categoryName}}
              </view>
            </scroll-view>
          </view>
          <view class="goods-list">
            <template v-if="productList && productList.length">
              <scroll-view scroll-y="true" :style="{width: '100%', height: `${goodsHeight}px;`}" @scrolltolower='loadMore'>
                <product-item v-for="pro in productList" :key="pro.id" :model="pro" @click='GOODS_DETAIL'></product-item>
				<view class="loading-more" v-if="loadingMore || nomore">
					{{ loadingMore ? '加载中...' : '没有更多了' }}
				</view>
              </scroll-view>
            </template>
            <template v-else>
              <view class="mt350">
                <tui-no-data :fixed="false" imgUrl="https://cwmall.oss-cn-shanghai.aliyuncs.com/mp-icon/img_noorder_3x.png">暂无商品
                </tui-no-data>
              </view>
            </template>
          </view>
        </view>
      </view>
    </template>
    <view class="mt350" v-else>
      <tui-no-data :fixed="false" imgUrl="https://cwmall.oss-cn-shanghai.aliyuncs.com/mp-icon/img_noorder_3x.png">
        暂无目录</tui-no-data>
    </view>

    <!-- 联系客服 -->
    <tui-customer></tui-customer>

    <custom-tab-bar name='category'></custom-tab-bar>
  </view>
</template>

<script>
import { mapState } from "vuex";
import ProductItem from "@/components/views/t-product-item/t-product-item.vue";
import { PRODUCTS_DETAIL } from "../../mixin/PRODUCTS_DETAIL";
import CustomTabBar from "@/components/common/custom-tabbar/custom-tabbar.vue";
import { JUST_ONSHOW } from '@/mixin/HOOKS.js'

export default {
  components: {
    ProductItem,
    CustomTabBar,
  },
  mixins: [PRODUCTS_DETAIL, JUST_ONSHOW],
  data() {
    return {
      tabbar: [],
      height: 0, //scroll-view高度
      top: 0,
      currentTab: "", //预设当前项的值
      selectedSubCateCode: "",
      selectedSubCateName: "",
      scrollViewId: "id_0",
      productList: [],
	  loadingMore: false,
	  nomore: false,
      pagination: {
        pageSize: 10,
        pageNum: 1,
        total: 0,
      },
    };
  },
  computed: {
    statusBar() {
      const {
        systemInfo: { statusBarHeight },
      } = this.$store.state;
      const menu = uni.getMenuButtonBoundingClientRect();
      return {
        top: statusBarHeight + (menu.top - statusBarHeight),
        height: menu.height + (menu.top - statusBarHeight),
        offset: menu.top - statusBarHeight,
        menuWidth: menu.width + uni.upx2px(14),
        menuHeight: menu.height,
      };
    },
    subCateScrollWidth() {
      const {
        systemInfo: { screenWidth },
      } = this.$store.state;
      return screenWidth - uni.upx2px(200) - uni.upx2px(50);
    },
    goodsHeight() {
      return this.height - uni.upx2px(110);
    },
    subCategory() {
      const sub = this.tabbar[this.currentTab]?.children || [];
      return sub;
    },
    ...mapState({
      merchantId: (state) => state.merchantId,
    }),
  },
  onLoad: function (options) {
    setTimeout(() => {
      this.init();
    }, 50);
    const {
      systemInfo: { statusBarHeight, windowHeight, safeAreaInsets },
    } = this.$store.state;
    // console.log(systemInfo, 'systeminfo')
    this.height =
      windowHeight -
      (this.statusBar.top + this.statusBar.height + 5) -
      (50 + safeAreaInsets.bottom);
	  
  },
  onShow() {
    const { CLASSIFY_PAGES_PARAMS } = this.$store.state;
    if (
      CLASSIFY_PAGES_PARAMS &&
      Object.prototype.toString.call(CLASSIFY_PAGES_PARAMS) ===
        "[object Object]" &&
      JSON.stringify(CLASSIFY_PAGES_PARAMS) !== "{}"
    ) {
      const { currentTab } = CLASSIFY_PAGES_PARAMS;
      if (typeof currentTab === "number") {
        this.currentTab = currentTab;
        // this.selectDefaultSubCate();
      }

      setTimeout(() => {
        this.$store.dispatch("CLASSIFY_PAGES_PARAMS", {});
      }, 500);
    } else {
      this.currentTab = 0;
      // this.selectDefaultSubCate();
    }
    this.getActiveNav();
  },
  methods: {
	CUSTOM_HOOK_SHOW() {
		this.initPagination();
		this.GetCateList();
	},
    // init接口
    init() {
      this.GetCateList();
    },
	initPagination() {
		this.pagination.pageNum = 1;
		this.nomore = false;
		this.loadingMore = false;
	},
    // 查询商家目录
    async GetCateList() {
      const { data } = await this.$api.GetCateList();
      // this.tabbar = data.filter(d => d.children && d.children.length)
      this.tabbar = data;
      // 默认选中第一个二级类目
      this.selectDefaultSubCate();
    },
    selectDefaultSubCate() {
      const children = this.tabbar[this.currentTab]?.children || [];
      if (children && children.length) {
        this.selectedSubCateCode = children[0].categoryCode;
        this.selectedSubCateName = children[0].categoryName;
        this.GetProductsByCate();
      } else {
        this.productList = [];
      }
    },
    // 点击标题切换当前页时改变样式
    swichNav: function (e) {
      // console.log(e, 'eeee')
      let cur = e.currentTarget.dataset.current;
      if (this.currentTab == cur) {
        return false;
      } else {
        this.currentTab = cur;
		this.initPagination();
        this.selectDefaultSubCate();
        this.checkCor();
        this.setActiveNav();
      }
    },
    setActiveNav() {
      uni.setStorage({
        key: "classify_first_nav",
        data: this.currentTab,
        success: function () {},
      });
    },
    getActiveNav() {
      const value = uni.getStorageSync("classify_first_nav");
      if (value) {
        this.currentTab = value;
      }
    },
    //判断当前滚动超过一屏时，设置tab标题滚动条。
    checkCor: function () {
      if (this.currentTab > 6) {
        this.scrollViewId = `id_${this.currentTab - 2}`;
      } else {
        this.scrollViewId = `id_0`;
      }
    },
    subCateTaped(cate) {
      this.selectedSubCateCode = cate.categoryCode;
      this.selectedSubCateName = cate.categoryName;
	  this.initPagination();
      this.GetProductsByCate();
    },
    // toProductList(e, row) {
    // 	let key = e.currentTarget.dataset.key;
    // 	console.log(e, row)
    // 	uni.navigateTo({
    // 		url: `../productList/productList?searchKey=${key}&categoryCode=${row.categoryCode}`
    // 	});
    // },
    // 根据类别分页查询商品列表
    async GetProductsByCate() {
      const {
        selectedSubCateCode = "",
        selectedSubCateName = "",
        pagination: { pageNum, pageSize },
      } = this.$data;
      let { data } = await this.$api.GetProductsByCate({
        categoryCode: selectedSubCateCode,
        // keyword: selectedSubCateName,
        pageNum,
        pageSize,
        merchantId: this.merchantId,
      });
      this.productList = pageNum === 1 ? data : this.productList.concat(data || [])
	  this.loadingMore = false;
	  if (!data || !data.length) {
		  this.nomore = true
	  }
    },
	loadMore() {
		if (!this.loadingMore && !this.nomore) {
			this.loadingMore = true;
			this.pagination.pageNum++
			this.GetProductsByCate()
		}
	}
  }
};
</script>

<style lang="scss">
page {
  background: #fcfcfc;
  height: 100%;
}

.container {
  display: flex;
  flex-direction: column;

  /* 头部 搜索栏 */
  .tui-searchbox {
    width: 100%;
    padding: 0 30rpx 10rpx;
    box-sizing: border-box;
    background: #fff;
    border-bottom: 1px solid #ddd;
    /* #ifdef H5 */
    top: 44px;

    /* #endif */
    &::after {
      content: "";
      position: absolute;
      border-bottom: 1rpx solid #d2d2d2;
      -webkit-transform: scaleY(0.5);
      transform: scaleY(0.5);
      bottom: 0;
      right: 0;
      left: 0;
    }

    .tui-search-bar {
      height: 60rpx;
      display: flex;
      align-items: center;

      .tui-search-input {
        width: 100%;
        height: 60rpx;
        background: #f1f1f1;
        border-radius: 30rpx;
        font-size: 26rpx;
        color: #999;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-left: 20rpx;

        .tui-search-text {
          padding-left: 16rpx;
        }
      }
    }
  }

  .tui-page-content {
    flex: 1;
    height: 0;
    overflow: hidden;
    display: flex;
    flex-direction: row;
    height: 100%;

    .tui-content-left {
      width: 200rpx;
      height: 100%;
      background-color: #f6f6f6;
      box-shadow: 0 12px 16px 0 rgba(0, 0, 0, 0.12);
      z-index: 9;
      position: relative;

      .tab-bar-item {
        width: 200rpx;
        height: 110rpx;
        background: #f6f6f6;
        box-sizing: border-box;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 26rpx;
        color: #444;
        font-weight: 400;
      }

      .active {
        position: relative;
        color: #e41f19;
        font-size: 30rpx;
        font-weight: 500;
        background: #fcfcfc;

        &::before {
          content: "";
          position: absolute;
          border-left: 8rpx solid #e41f19;
          height: 30rpx;
          left: 0;
        }
      }
    }

    .tui-content-right {
      flex: 1;
      height: 100%;
      display: flex;
      flex-direction: column;

      .sub-categorys {
        z-index: 6;
        position: relative;
        max-height: 110rpx;
        min-height: 110rpx;
        overflow: hidden;
        padding: 0 30rpx 0 20rpx;
        background-color: #fff;
        box-shadow: 0 3px 10px 0 rgba(0, 0, 0, 0.12);

        .sub-category-scroller {
          white-space: nowrap;
          padding: 22rpx 0;

          .sub-category-item {
            font-size: 26rpx;
            border: 1px solid #f1f1f1;
            border-radius: 4rpx;
            background-color: #f1f1f1;
            padding: 13rpx;
            display: inline-block;
            margin-right: 17rpx;

            &.actived-sub-cate {
              color: #e41f19;
              background: rgba(228, 31, 25, 0.1);
              border-color: rgba(228, 31, 25, 0.1);
            }
          }
        }
      }

      .goods-list {
        flex: 1;
        overflow: hidden;
		.loading-more {
			display: flex;
			align-items: center;
			justify-content: center;
			height: 80rpx;
			color: #b1b1b1;
			font-size: 26rpx;
		}
      }
    }
  }
}

/* 隐藏scroll-view滚动条*/
::-webkit-scrollbar {
  width: 0;
  height: 0;
  color: transparent;
}

.page-view {
  width: 100%;
  overflow: hidden;
  padding-top: 20rpx;
  padding-right: 20rpx;
  box-sizing: border-box;
  padding-bottom: env(safe-area-inset-bottom);
}

.swiper {
  width: 100%;
  height: 220rpx;
  border-radius: 12rpx;
  overflow: hidden;
  transform: translateZ(0);
}

/* #ifdef MP-WEIXIN */
.swiper .wx-swiper-dot {
  width: 8rpx;
  height: 8rpx;
  display: inline-flex;
  background: none;
  justify-content: space-between;
}

.swiper .wx-swiper-dot::before {
  content: "";
  flex-grow: 1;
  background: rgba(255, 255, 255, 0.8);
  border-radius: 16rpx;
  overflow: hidden;
}

.swiper .wx-swiper-dot-active::before {
  background: #fff;
}

.swiper .wx-swiper-dot.wx-swiper-dot-active {
  width: 16rpx;
}

/* #endif */

/* #ifndef MP-WEIXIN */
>>> .swiper .uni-swiper-dot {
  width: 8rpx;
  height: 8rpx;
  display: inline-flex;
  background: none;
  justify-content: space-between;
}

>>> .swiper .uni-swiper-dot::before {
  content: "";
  flex-grow: 1;
  background: rgba(255, 255, 255, 0.8);
  border-radius: 16rpx;
  overflow: hidden;
}

>>> .swiper .uni-swiper-dot-active::before {
  background: #fff;
}

>>> .swiper .uni-swiper-dot.uni-swiper-dot-active {
  width: 16rpx;
}

/* #endif */

.slide-image {
  width: 100%;
  height: 220rpx;
}

.class-box {
  padding-top: 30rpx;
}

.class-item {
  background: #fff;
  width: 100%;
  box-sizing: border-box;
  padding: 20rpx;
  margin-bottom: 20rpx;
  border-radius: 12rpx;
}

.class-name {
  font-size: 22rpx;
}

.g-container {
  /* padding-top: 20rpx; */
  display: flex;
  display: -webkit-flex;
  justify-content: flex-start;
  flex-direction: row;
  flex-wrap: wrap;
}

.g-box {
  width: 33.3333%;
  text-align: center;
  padding-top: 40rpx;
}

.g-image {
  width: 120rpx;
  height: 120rpx;
}

.g-title {
  font-size: 22rpx;
}
</style>
